package com.example.myapplication;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class TeleplayAdapter extends RecyclerView.Adapter<TeleplayAdapter.ViewHolder> {
    //private final List<Tv> TvList;
    private List<Teleplay> mTeleplayList;
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //用来创建ViewHolder实例，再将加载好的布局传入构造函数，最后返回ViewHolder实例
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.teleplay_item,null);
        //ViewHolder holder=new ViewHolder(view);
        //监听器部分
        final ViewHolder holder=new ViewHolder(view);
        holder.teleplayView.setOnClickListener(new View.OnClickListener() {//item的监听器
            @Override
            public void onClick(View view) {
                int position=holder.getAdapterPosition();  //获取点击的位置
                Teleplay fruit=mTeleplayList.get(position);       //获取fruit
                Toast.makeText(view.getContext(), "你点击了"+fruit.getName(), Toast.LENGTH_SHORT).show();
            }
        });
        holder.teleplayImage.setOnClickListener(new View.OnClickListener() {//imageView的监听器
            @Override
            public void onClick(View view) {
                int position=holder.getAdapterPosition();  //获取点击的位置
                Teleplay fruit=mTeleplayList.get(position);       //获取fruit
                Toast.makeText(view.getContext(), "你点击了"+fruit.getName()+"的图片", Toast.LENGTH_SHORT).show();
            }
        });
        return holder;
    }
    public TeleplayAdapter(List<Teleplay> teleplayList){
        mTeleplayList=teleplayList;
        //mTeleplayList=mTeleplayList;
    }
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        //用于对RecyclerView的子项进行赋值，会在每个子项滚动到屏幕内的时候执行
        Teleplay teleplay=mTeleplayList.get(position);
        holder.teleplayImage.setImageResource(teleplay.getImageID());
        holder.teleplayName.setText(teleplay.getName());
    }

    @Override
    public int getItemCount() {
        return mTeleplayList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{
        public View teleplayView;  //监听相关：用来保存RecyclerView的子项最外层的实例
        ImageView teleplayImage;
        TextView teleplayName;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            teleplayView=itemView;//赋值
            teleplayImage=itemView.findViewById(R.id.tv_image);
            teleplayName=itemView.findViewById(R.id.tv_name);
        }
    }
}
